﻿using System.Collections.ObjectModel;
using Caliburn.Micro;
using Serialization;
using Wulong.Phone.Dianping.Models;

namespace Wulong.Phone.Dianping.ViewModels
{
    public class MainViewModelStorage : StorageHandler<MainViewModel>
    {
        public override void Configure()
        {
            Property(x => x.CityCode).InPhoneState().RestoreAfterViewReady();
            Property(x => x.CityPinyin).InPhoneState().RestoreAfterViewReady();
            
            AddInstruction().Configure(x =>
            {
                x.Key = "groupon";

                x.Save = (instance, getKey, mode) =>
                {
                    var value = SilverlightSerializer.Serialize(instance._groupOnList);
                    x.StorageMechanism.Store(getKey(), value);
                };
                x.Restore = (instance, getKey, mode) =>
                {
                    object value;
                    var key = getKey();

                    if (x.StorageMechanism.TryGet(key, out value))
                    {
                        instance._groupOnList = (value == null)
                                                    ? null
                                                    : SilverlightSerializer.
                                                          Deserialize(
                                                              (byte[])value) as ObservableCollection<GroupOn>;

                        x.StorageMechanism.Delete(key);
                    }

                };
            }).InPhoneState().RestoreAfterViewReady();

            AddInstruction().Configure(x =>
            {
                x.Key = "hotpromotion";

                x.Save = (instance, getKey, mode) =>
                {
                    var value = SilverlightSerializer.Serialize(instance._hotPromotionList);
                    x.StorageMechanism.Store(getKey(), value);
                };
                x.Restore = (instance, getKey, mode) =>
                {
                    object value;
                    var key = getKey();

                    if (x.StorageMechanism.TryGet(key, out value))
                    {
                        instance._hotPromotionList = (value == null)
                                                    ? null
                                                    : SilverlightSerializer.
                                                          Deserialize(
                                                              (byte[])value) as ObservableCollection<Promotion>;

                        x.StorageMechanism.Delete(key);
                    }

                };
            }).InPhoneState().RestoreAfterViewReady();
        }
    }
}
